﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Data;
using System.Drawing;
using Infragistics.WebUI.UltraWebGrid;
using System.Configuration;

public partial class QtyAdjustPopupForm : System.Web.UI.Page
{
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESRejectAppBusiness rejectapp = new uMESRejectAppBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    string businessName = "批次管理", parentName = "Container";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Dictionary<string, string> popupData = (Dictionary<string, string>)Session["PopupData"];
            txtDispProcessNo.Text = popupData["ProcessNo"].ToString();
            txtDispOprNo.Text = popupData["OprNo"].ToString();
            txtDispContainerID.Text = popupData["ContainerID"].ToString();
            txtDispContainerName.Text = popupData["ContainerName"].ToString();
            txtDispProductName.Text = popupData["ProductName"].ToString();
            txtDispDescription.Text = popupData["Description"].ToString();
            txtDispContainerQty.Text = popupData["Qty".ToString()].ToString();
            txtDispPlannedStartDate.Text = popupData["PlannedStartDate"].ToString();
            txtDispPlannedCompletionDate.Text = popupData["PlannedCompletionDate"].ToString();
            txtChildCount.Text = popupData["ChildCount"].ToString();
            txtDispWorkflowID.Text = popupData["WorkflowID"].ToString();
            txtDispWorkflowName.Text = popupData["WorkflowName"].ToString();
            txtDispWorkflowRev.Text = popupData["WorkflowRev"].ToString();
            txtDispStepName.Text = popupData["StepName"].ToString();
            txtDispProductRev.Text = popupData["ProductRev"].ToString();

            Session["PopupData"] = null;
            Session["ContainerMessage"] = null;
            string strChildCount = txtChildCount.Text;
            if (strChildCount == "0")
            {
                BindQtyAdjustReason();
                wgProductNoList.Visible = false;

                btnAdd.Visible = false;
                btnDel.Visible = false;
            }
            else
            {
                txtQty.Attributes.Add("readonly", "readonly");
                trQty.Visible = false;

                string strContainerID = txtDispContainerID.Text;
                DataTable dtProductNo = common.GetProductNo(strContainerID);

                wgProductNoList.DataSource = dtProductNo;
                wgProductNoList.DataBind();
            }

            hdSuccess.Value = "";
            //txtScrapInfoName.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        }
    }

    protected void BindQtyAdjustReason()
    {
        DataTable dt = common.GetQtyAdjustReason();
        dt.Columns.Add("qtyadjustreasonname");
        ddlQtyAdjust.DataSource = dt;
        ddlQtyAdjust.DataTextField = "qtyadjustreasonname";
        ddlQtyAdjust.DataValueField = "qtyadjustreasonname";
        ddlQtyAdjust.DataBind();
    }
    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        lStatusMessage.Text = strMessage;

        if (boolResult == true)
        {
            lStatusMessage.ForeColor = Color.Black;
        }
        else
        {
            lStatusMessage.ForeColor = Color.Red;
        }
    }
    #endregion

    #region 提交按钮
    protected void btnMaterialApp_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strOprEmployeeID = userInfo["EmployeeID"];
            string strEmployeeName = userInfo["ApiEmployeeName"];
            string strPassword = userInfo["ApiPassword"];
            string strContainerName = txtDispContainerName.Text;
            string strChildCount = txtChildCount.Text;

            if (strChildCount == "0")
            {
                string strQty = txtQty.Text.Trim();
                int intNewQty = 0;

                if (strQty.Contains("."))
                {
                    ShowStatusMessage("数量必须为整数", false);
                    return;
                }
                else
                {
                    try
                    {
                        intNewQty = Convert.ToInt32(strQty);

                        if (intNewQty <= 0)
                        {
                            ShowStatusMessage("数量应大于零", false);
                            return;
                        }
                    }
                    catch
                    {
                        ShowStatusMessage("数量必须为数字", false);
                        return;
                    }
                }
                if (ddlQtyAdjust.Items.Count == 0)
                {
                    ShowStatusMessage("数量调整原因不能为空", false);
                    return;
                }
                if (ddlQtyAdjust.SelectedItem.Value == null)
                {
                    ShowStatusMessage("数量调整原因不能为空", false);
                    return;
                }

                int intOldQty = Convert.ToInt32(txtDispContainerQty.Text);

                int intAdjustQty = intNewQty - intOldQty;
                string strReasonCode = ddlQtyAdjust.SelectedItem.Text;// ConfigurationManager.AppSettings["DefaultQtyAdjustReason"].ToString();

                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ContainerName", strContainerName);
                para.Add("Level", "Lot");
                para.Add("ServerUser", strEmployeeName);
                para.Add("ServerPassword", strPassword);

                DataTable dtChangeQtyDetails = new DataTable();
                dtChangeQtyDetails.Columns.Add("Qty");
                dtChangeQtyDetails.Columns.Add("ReasonCode");

                DataRow r = dtChangeQtyDetails.NewRow();
                r["Qty"] = intAdjustQty.ToString();
                r["ReasonCode"] = strReasonCode;
                dtChangeQtyDetails.Rows.Add(r);

                string strInfo = string.Empty;
                Boolean result = rejectapp.ChangeQty(para, dtChangeQtyDetails, "Adjust", out strInfo);
                if (result == false)
                {
                    ShowStatusMessage(strInfo, false);
                    return;
                }

                #region 记录日志
                var ml = new MESAuditLog();
                ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtDispContainerID.Text;
                ml.ParentID = ml.ContainerID; ml.ParentName = parentName;
                ml.CreateEmployeeID = userInfo["EmployeeID"];
                ml.BusinessName = businessName; ml.OperationType = 1;
                ml.Description = "批次数量更改:" + "更改到:"+ txtQty.Text;
                common.SaveMESAuditLog(ml);
                #endregion

            }
            else
            {
                string strContainerID = txtDispContainerID.Text;
                DataTable dtProductNo = common.GetProductNo(strContainerID);

                //需要新增的产品序号
                List<string> listAdd = new List<string>();

                for (int i = 0; i < wgProductNoList.Rows.Count; i++)
                {
                    string strProductNo = wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value.ToString();
                    string strChildName = strContainerName + strProductNo;

                    Boolean isAdd = true;
                    foreach (DataRow row in dtProductNo.Rows)
                    {
                        string strCName = row["ContainerName"].ToString();
                        if (strCName == strChildName)
                        {
                            isAdd = false;
                            break;
                        }
                    }

                    if (isAdd == true)
                    {
                        listAdd.Add(strChildName);
                    }
                }

                if (listAdd.Count > 0 && hdSuccess.Value == "")
                {
                    foreach (string strChild in listAdd)
                    {
                        //创建批次
                        StartContainer(strChild);

                        //非标准移动
                        Dictionary<string, string> para2 = new Dictionary<string, string>();
                        para2.Add("ContainerName", strChild);
                        para2.Add("WorkflowName", txtDispWorkflowName.Text);
                        para2.Add("WorkflowRev", txtDispWorkflowRev.Text);
                        para2.Add("StepName", txtDispStepName.Text);
                        para2.Add("ServerUser", strEmployeeName);
                        para2.Add("ServerPassword", strPassword);

                        string strInfo = string.Empty;
                        Boolean r = rejectapp.MoveNonStd(para2, out strInfo);
                    }

                    //关联
                    Dictionary<string, string> para = new Dictionary<string, string>();
                    para.Add("ContainerName", strContainerName);
                    para.Add("ServerUser", strEmployeeName);
                    para.Add("ServerPassword", strPassword);

                    string strMessage = string.Empty;

                    Boolean result = rejectapp.AssociateOrDisassociate(para, listAdd, "Associate", out strMessage);
                    if (result)
                    {
                        hdSuccess.Value = "Success";
                    }
                }

                //需要取消关联的产品序号
                List<string> listDel = new List<string>();

                string strDelContainer = string.Empty;

                foreach (DataRow row in dtProductNo.Rows)
                {
                    string strChildName = row["ContainerName"].ToString();

                    Boolean isDel = true;
                    for (int i = 0; i < wgProductNoList.Rows.Count; i++)
                    {
                        string strProductNo = wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value.ToString();
                        string strCName = strContainerName + strProductNo;

                        if (strCName == strChildName)
                        {
                            isDel = false;
                            break;
                        }
                    }

                    if (isDel == true)
                    {
                        listDel.Add(strChildName);
                        if (strDelContainer.Contains("'" + strChildName + "',") == false)
                        {
                            strDelContainer += "'" + strChildName + "',";
                        }
                    }
                }

                if (listDel.Count > 0)
                {
                    Dictionary<string, string> para = new Dictionary<string, string>();
                    para.Add("ContainerName", strContainerName);
                    para.Add("ServerUser", strEmployeeName);
                    para.Add("ServerPassword", strPassword);

                    string strMessage = string.Empty;
                    if (hdSuccess.Value == "")
                    {
                        Boolean result = rejectapp.AssociateOrDisassociate(para, listDel, "Disassociate", out strMessage);
                        if (result == false)
                        {
                            ShowStatusMessage(strMessage, false);
                            return;
                        }
                        hdSuccess.Value = "Success";
                    }


                    //将取消关联的子批次状态置为 2； 数量置为 0
                    if (strDelContainer != "")
                    {
                        strDelContainer = strDelContainer.TrimEnd(',');
                        int intResult = common.UpdateContainerState(strDelContainer);
                    }
                }
            }

            Session["ContainerMessage"] = "数量调整成功！";
            Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    #region 批次创建 
    ResultModel StartContainer(string strContainerName)
    {
        ResultModel result = new ResultModel(false, "");

        string productName = txtDispProductName.Text;
        string productRev = txtDispProductRev.Text;

        ContainerStartModel containerStart = new ContainerStartModel();
        containerStart.ContainerName = strContainerName;
        containerStart.Level = "Lot";
        containerStart.ProductName = productName;
        containerStart.ProductRev = productRev;

        string strOwner = ConfigurationManager.AppSettings["DefaultOwner"].ToString();
        containerStart.Owner = strOwner;
        containerStart.Qty = 1;

        string strUom = ConfigurationManager.AppSettings["DefaultUom"].ToString();
        containerStart.Uom = strUom; //单位

        string strStartReason = ConfigurationManager.AppSettings["DefaultStartReason"].ToString();
        containerStart.StartReason = strStartReason;


        string workflowName = txtDispWorkflowName.Text;
        string workflowRev = txtDispWorkflowRev.Text;

        containerStart.WorkflowName = workflowName;
        containerStart.WorkflowRev = workflowRev;

        string strMfgOrderName = "";
        containerStart.Mfgorder = strMfgOrderName;


        if (string.IsNullOrWhiteSpace(txtDispPlannedStartDate.Text) == false)
        {
            containerStart.PlannedStartDate = txtDispPlannedStartDate.Text;
        }

        if (string.IsNullOrWhiteSpace(txtDispPlannedCompletionDate.Text) == false)
        {
            containerStart.PlannedCompletionDate = txtDispPlannedCompletionDate.Text;
        }

        containerStart.ContainerComment = "";
        //子批次

        DataTable childDt = new DataTable();
        childDt.Columns.Add("ContainerName");
        childDt.Columns.Add("Qty");
        childDt.Columns["Qty"].DefaultValue = 1;

        containerStart.ChildList = childDt;

        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strOprEmployeeID = userInfo["EmployeeID"];
        string strEmployeeName = userInfo["EmployeeName"];
        string strPassword = userInfo["Password"];
        containerStart.StartEmployee = strEmployeeName;

        result = containerBal.StartContainer(containerStart, strEmployeeName, strPassword);
        if (result.IsSuccess)
            result.Message = "批次" + containerStart.ContainerName + "创建完成";

        return result;
    }
    #endregion

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        wgProductNoList.Rows.Add();

        wgProductNoList.Rows[wgProductNoList.Rows.Count - 1].Cells.FromKey("ProductNo").AllowEditing = AllowEditing.Yes;

    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        TemplatedColumn temCell1 = (TemplatedColumn)wgProductNoList.Columns.FromKey("ckSelect");

        for (int i = temCell1.CellItems.Count - 1; i >= 0; i--)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem1 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell1.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem1.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                wgProductNoList.Rows.RemoveAt(i);
            }
        }
    }
}